<?php

namespace app\common\model;


use think\Model;
use think\Db;

//排行榜
class SortModel extends Model
{

    protected $name = '';


    //赛季排行榜
    public function season_ranking(){

        $data = db('activity')->where(['status'=>1])->find();//正在进行的活动
        //$date = date('Y-m-d',time());//按天
        //$end_date = date('Y-m-d',$data['end_time']);
        $date = time();//
        $end_date = $data['end_time'];
        if(!empty($data) && $end_date < $date){//过期活动
            $res = db('activity')->where(['id'=>$data['id']])->update(['status'=>'-1']);//关闭该活动
            //开启最近的新活动
            //$res = db('activity')->where("start_time<='{$date}' and end_time>='{$date}'")->limit(1)->update(['status'=>'1']);//
            $table = config('database.prefix').'activity';//表
            $res = Db::execute("UPDATE {$table} set status=1 where  start_time<='{$date}' and end_time>='{$date}' limit 1");
            //结算赛季数据
            $sort_data = db('user')
                    ->field('id as user_id,grad_id,grad_name,count_changshu,count_wins,curr_grad_start')
                    ->order([
                        'grad_id'         => 'desc',
                        'curr_grad_start' => 'desc',
                        'count_wins'      => 'desc'
                    ])->limit(100)->select();
            foreach ($sort_data as $key => $value) {
                $sort_data[$key]['aid']=$data['id'];//活动赛季id
                $sort_data[$key]['create_time']=time();
            }
            $res = db('season_ranking_log')->where("aid>0")->delete();//清除上一赛季数据
            $res_status = db('season_ranking_log')->insertAll($sort_data); 
            //重置用户上赛季数据
            if($res_status){
                $first_grad = db('grad')->order('id')->find();//第一段位
                $up_data = [
                    'grad_id'=>$first_grad['id'],
                    'grad_name'=>$first_grad['name'],
                    'curr_grad_start'=>0
                ];
                $ret = db('user')->where('grad_id>0')->update($up_data);
                return true;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }
    
}